import {
  Component,
  Injector,
  ViewEncapsulation,
  ViewChild,
  OnInit,
  EventEmitter,
  Output,
  ElementRef
} from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import {
  MaterialReturnServiceProxy,
  LocationDto,
  LocationServiceProxy
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'yl10ChildModal',
  templateUrl: './yl10-modal.component.html',
  encapsulation: ViewEncapsulation.None
})
export class YL10ChildModalComponent extends AppComponentBase {
  @ViewChild('secondModal') modal: ModalDirective;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;

  chargeId = '';
  outId = '';

  positionId = 0;

  quantity = 0;
  remark = '';
  canReturnQuantity = 0;
  pipeId = '';

  constructor(
    injector: Injector,
    private _returnMaterialServiceProxy: MaterialReturnServiceProxy
  ) {
    super(injector);
  }

  show(
    pipeId: string,
    outId: string,
    chargeId: string,
    canReturnQuantity: number
  ): void {
    this.positionId = 0;

    this.active = true;
    this.quantity = 0;
    this.remark = '';
    this.chargeId = chargeId;
    this.outId = outId;
    this.pipeId = pipeId;
    this.canReturnQuantity = canReturnQuantity;
    // console.log(canReturnQuantity);
    setTimeout(() => {
      this.modal.show();
    }, 0);
  }

  save(): void {
    if (!this.positionId) {
      this.notify.error('请选择一个位置');
      return;
    }

    if (!this.quantity) {
      this.notify.error('退库数量不能为0');
      return;
    }
    if (this.quantity > this.canReturnQuantity) {
      this.notify.error('退库数量不能大于可退库数量');
      return;
    }

    this.saving = true;

    this._returnMaterialServiceProxy
      .returnWarehouse(
        this.pipeId,
        this.outId,
        this.chargeId,
        this.positionId,
        this.quantity,
        this.remark
      )
      .pipe(
        finalize(() => {
          this.saving = false;
        })
      )
      .subscribe(result => {
        this.close();
        this.modalSave.emit(null);
        this.notify.success('退库成功');
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
